/* ImportPlainFileAction.java
 * Author: liuex
 * 2007-12-20 ����12:50:31
 *
 * Note: 
 */
package lex.proxyverfier.importexport;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;

import org.lex.net.proxy.ProxyServer;


public class ImportFromPlainFile extends AbstractImportProxyServer
{
	@Override
	public List<ProxyServer> importProxyServers( BufferedReader in ) throws IOException
	{
		ArrayList<ProxyServer> list = new ArrayList<ProxyServer>();
		String line = null;
		while( true )
		{
			try
			{
				line = in.readLine();
			}
			catch( Exception ex )
			{
				return list;
			}
			if( null == line )
				return list;
			ProxyServer ps = this.parseLine( line );
			if( null != ps )
				list.add( ps );
		}
	}

	/*
	 * {name} {type} {host} {port} <br> {name} may contains white-spaces
	 */
	private ProxyServer parseLine( String line )
	{
		try
		{
			int start = line.lastIndexOf( ' ' );
			int port = Integer.parseInt( line.substring( start + 1 ) );
			// host
			int end = start;
			start = line.lastIndexOf( ' ', end - 1 );
			String host = line.substring( start + 1, end );
			// type
			end = start;
			start = line.lastIndexOf( ' ', end - 1 );
			String type = line.substring( start + 1, end ).toUpperCase();
			// name
			end = start;
			String name = line.substring( 0, end );
			// combine them
			return new ProxyServer( name, Proxy.Type.valueOf( type ), host, port );
		}
		catch( Exception e )
		{
			return null;
		}
	}
}
